<template>
  <div class="root">
    <!--功能按钮-->
    <div class="util">
      <el-button @click="fanHui">返回</el-button>
      <el-button type="primary">保存并新增</el-button>
      <el-button @click="save">保存</el-button>
    </div>

    <!--第一行-->
    <el-row class="el-rows">
      <el-col :span="8">
        供应商：<input @click="showSupplier = true" type="text" class="ipt" v-model="purchase.supplierName" />
      </el-col>
      <el-col :span="8">
        单据日期：<el-date-picker value-format="YYYY-MM-DD" type="date" placeholder="Pick a day"
          v-model="purchase.billDate" />
      </el-col>
      <el-col :span="8"> 单据编号：CG01234 </el-col>
    </el-row>

    <!--采购明细-->
    <div class="detail">
      <!--第一行-->
      <div class="detail-title">
        <span>采购明细</span>
        <el-button size="small" @click="addRow" style="margin-left: 10px">增行</el-button>
        <el-button size="small" @click="del">删行</el-button>
      </div>

      <!--采购明细表格-->
      <div>
        <el-table :data="tableData" ref="tableRef" style="width: 100%" border stripe @cell-click="dbcell"
          :header-cell-style="{
        'text-align': 'center',
        'font-size': '14px',
        color: '#666666',
        borderColor: '#e0e0e0',
      }" :cell-style="{
        'text-align': 'center',
        'font-size': '12px',
        color: '#666666',
        borderColor: '#e0e0e0',
      }">
          <el-table-column type="selection" width="80" />

          <el-table-column type="index" label="序号" width="80" />

          <el-table-column prop="goodsname" label="商品">
            <template v-slot="{ row, column }">
              <span v-if="row.show[column.property] == undefined">{{ row.goodsname }}</span>
              <el-input @click="showGoods = true" v-else v-model="row.goodsname" @blur="row.show = {}"></el-input>
            </template>
          </el-table-column>

          <el-table-column prop="unit" label="单位" width="100" />
          <el-table-column prop="warehouse" label="仓库(批量)" width="150" />
          <el-table-column prop="num" label="数量" width="100">
            <template v-slot="{ row, column }">
              <span v-if="row.show[column.property] == undefined">{{ row.num }}</span>
              <el-input v-else v-model="row.num" @blur="row.show = {}" type="number" :min="0"></el-input>
            </template>
          </el-table-column>

          <el-table-column prop="price" label="采购单价" width="120">

          </el-table-column>

          <el-table-column prop="rate" label="折扣率(%)" width="100">
            <template v-slot="{ row, column }">
              <span v-if="row.show[column.property] == undefined">{{ row.rate }}</span>
              <el-input v-else v-model="row.rate" @blur="row.show = {}"></el-input>
            </template>
          </el-table-column>

          <el-table-column prop="rateMoney" label="折扣额" width="120">

          </el-table-column>

          <el-table-column prop="money" label="采购金额" width="120">

          </el-table-column>

          <el-table-column prop="note" label="备注" width="180">
            <template v-slot="{ row, column }">
              <span v-if="row.show[column.property] == undefined">{{ row.note }}</span>
              <el-input v-else v-model="row.note" @blur="row.show = {}"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!--订单备注信息-->
    <div class="detail-note">
      <input type="text" placeholder="填写订单备注信息" class="note" v-model="purchase.note" />
    </div>

    <!--优惠率-->
    <el-row class="el-rows">
      <el-col :span="4">优惠率：<input type="text" class="ipt" v-model="purchase.rate" />%</el-col>
      <el-col :span="4">优惠金额：<input type="text" class="ipt" v-model="purchase.rateMoney" /></el-col>
      <el-col :span="4">优惠后金额：<input type="text" class="ipt" v-model="purchase.money" /></el-col>
      <el-col :span="12">本次付款：<input type="text" class="ipt" v-model="purchase.pay" /></el-col>
    </el-row>

    <!--结算账户-->
    <el-row class="el-rows">
      <el-col :span="4">结算账户：<input type="text" class="ipt" v-model="purchase.accountId" /></el-col>
      <el-col :span="4">本次欠款：<input type="text" class="ipt" v-model="purchase.debt" /></el-col>
      <el-col :span="16">
        <span>采购合同：</span>
        <div class="upload">
          <el-upload v-model:file-list="fileList" :action="host + '/upload'" :on-success="handleChange" :on-remove="rm">
            <el-button type="primary" style="margin-left: 10px">上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                jpg/png 格式的文件
              </div>
            </template>
          </el-upload>
        </div>


        <el-button>查看</el-button>
      </el-col>
    </el-row>

    <!--制单人-->
    <el-row class="el-rows">
      <el-col :span="4">制单人：<input type="text" class="ipt" v-model="purchase.prepared" /></el-col>
      <el-col :span="20">&nbsp;</el-col>
    </el-row>

    <!--商品选择组件-->
    <chooseGoods :dialogVisible="showGoods" @close="showGoods = false" @choose="chooseGood"></chooseGoods>

    <!--供应商组件-->
    <chooseSupplier :dialogVisible="showSupplier" @close="showSupplier = false" @choose="chooseSup"></chooseSupplier>
  </div>
</template>

<script setup>
import chooseSupplier from "@/views/set/supplier/chooseSupplier.vue";
import chooseGoods from "@/views/set/goods/chooseGoods.vue";
import { ref, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import { savePurchase } from "@/api/purchase/purchase.js";
import host from '@/utils/env.js'
import { useRouter } from "vue-router";
//属性区
//路由跳转
const router = useRouter()
//组件显示
const showGoods = ref(false); //商品选择组件
const showSupplier = ref(false); //选择供应商组件
//table引用
const tableRef = ref(null);
//采购明细列表
const tableData = ref([]);
//订单对象
const purchase = ref({
  supplierId: 0,
  supplierName: "",
  billDate: "",
  note: "",
  rate: 0,
  rateMoney: 0,
  money: 0,
  pay: 0,
  accountId: 0,
  debt: 0,
  prepared: "",
  contracts: [],
});

//上传的合同
const fileList = ref([])

//侦听table
watch(
  tableData,
  (n) => {
    //遍历表格明细，计算折扣额，采购金额
    tableData.value.forEach((r) => {
      if (r.num > 0 && r.price > 0) {
        //原价
        let total = r.num * r.price;
        //计算折扣额
        let tmpRateMoney = 0;
        if (r.rate > 0) {
          tmpRateMoney = total * (r.rate / 100);
          //更新折扣额
          r.rateMoney = tmpRateMoney;
        }
        //计算采购金额
        r.money = total - tmpRateMoney;
      }
    });
  },
  { deep: true }
);

//方法区

//删除合同
let rm = (uploadFile) => {
  // console.log(uploadFile)
  purchase.value.contracts = purchase.value.contracts.filter((f) => {
    return f.path != uploadFile.response.data
  })
}

//上传合同事件
let handleChange = (res, uploadFile) => {
  if (res.code == 200) {
    //上传成功
    let tmp = {}
    tmp.path = res.data
    tmp.filename = uploadFile.name
    purchase.value.contracts.push(tmp)
  }
}

//选择供应商事件
let chooseSup = (row) => {
  purchase.value.supplierId = row.id;
  purchase.value.supplierName = row.name;
};

//选择商品事件
let chooseGood = (rows) => {

  if (rows.length == 0) return;

  //点击的行的下标
  let index = -1;

  //遍历表格数据，查询选择的第一个对象的位置
  for (let i = 0, len = tableData.value.length; i < len; i++) {
    let tmp = tableData.value[i];
    if (tmp == lastRow.value) {
      index = i;
      break;
    }
  }

  if (index == -1) {
    return;
  }

  //遍历选择的商品
  for (let i = 0, len = rows.length; i < len; i++) {
    //临时对象
    let obj = tableData.value[index];

    obj.goodsid = rows[i].id;
    obj.goodsname = rows[i].name;
    obj.price = rows[i].price;
    obj.unit = rows[i].unit;
    obj.warehouse = rows[i].warehouseName;
    index++;
  }

  //先清空之前 添加的所有属性
  if (lastRow.value.show != undefined) {
    //清空标志属性
    lastRow.value.show = {};
  }
};

//增行方法
let addRow = () => {
  tableData.value.push({
    goodsId: "",
    goodsname: "",
    unit: "",
    warehouse: "",
    num: 0,
    price: 0,
    rate: 0,
    rateMoney: 0,
    money: 0,
    note: "",
    show: {},
  });
};

//删行
let del = () => {
  let rows = tableRef.value.getSelectionRows();
  if (rows.length == 0) {
    ElMessage({
      message: "请选择要删除的行！",
      type: "warning",
    });
  }

  rows.forEach((r) => {
    remove(r);
  });
};
//删除方法
let remove = (r) => {
  tableData.value = tableData.value.filter((item) => {
    return item != r;
  });
};

//初始化方法 表格10行
let init = () => {
  for (let i = 1; i <= 10; i++) {
    addRow();
  }
};
//上次点击的是哪一行
const lastRow = ref({});

//表格双击事件
let dbcell = (row, column) => {
  //如果不为空 清除
  if (lastRow.value.show != undefined) {
    lastRow.value.show = {};
  }

  let tmp = column.property;
  row.show[tmp] = true;
  //记录双击的这一行
  lastRow.value = row;
};

//保存方法
let save = async () => {
  // console.log(purchase.value)
  // return;
  let detail = []; //保存商品明细
  //遍历表格数据
  tableData.value.forEach((r) => {
    //判断是否有商品
    if (r.goodsname != undefined && r.goodsname != "") {
      detail.push(r);
    }
  });

  if (detail.length == 0) {
    ElMessage({
      message: "采购明细不能为空！",
      type: "warning",
    });
    return;
  }
  //data传递的参数
  let data = purchase.value;
  //订单明细加入data中
  data.purchaseDetailList = detail;

  //发送请求
  let res = await savePurchase(data);
  if (res.code == 200) {
    ElMessage({
      message: "保存成功",
      type: "success",
    });
  }
};

//返回
let fanHui = () => {
  router.push("/purchase/index")
}

//生命周期
onMounted(() => {
  init();
});
</script>

<style scope>
* {
  padding: 0;
  margin: 0;
}

.root {
  border: 1px solid #ccc;
  height: 100%;
  background-color: #fff;
  padding-left: 30px;
}

.util {
  margin-top: 10px;
  text-align: right;
  margin-right: 40px;
}

.el-rows {
  margin-top: 30px;
  font-size: 14px;
  color: #666666;
}

.el-rows :last-child {
  margin: 0;
  /* color:red; */

}

.ipt {
  outline-style: none;
  border-style: none;
  border-bottom: 1px solid #ccc;
  width: 150px;
  /* padding-left: 20px; */
}

.detail {
  border: #e0e0e0 1px solid;
  margin-top: 30px;
  margin-right: 200px;
}

.detail-title {
  margin-left: 10px;
  font-size: 14px;
  color: #666666;
  height: 40px;
  line-height: 40px;
  /* border-bottom: 1px solid #e0e0e0; */
}

.detail-note {
  border: none;
  border-bottom: #e0e0e0 1px solid;
  margin-top: 20px;
  margin-right: 200px;
}

.note {
  width: 100%;
  height: 40px;
  border-style: none;
  outline-style: none;
}

.upload {
  display: inline-flex;
}
</style>
